﻿@using CleanArchitecture.Core.Helper
@using CleanArchitecture.Infrastructure.Entities
@using CleanArchitecture.Infrastructure.Models.SystemManage
@model SystemModuleModel
@{
    Layout = "_BackendLayout";
    ViewData["Title"] = ViewBag.PageTitle as string;
    var datadicButtons = Model.CustomProperties["buttonModels"] as SystemDataDicButtonListModel ?? null;
    var SystemModuleAssignedButtons = Model.ModuleAssignedButtons == null || Model.ModuleAssignedButtons.Count == 0
                                    ? string.Empty
                                    : string.Join(",", Model.ModuleAssignedButtons.ToArray());
}
@section cssstyles {
    <style type="text/css">
        body {
            margin: 5px !important;
            display: flex;
            flex: auto;
            flex-direction: column;
            min-height: 0;
            background: #f0f2f5;
        }
        .layui-form-item { margin-bottom: 5px; }
        .layui-form-item .layui-form-select { float: left; width: 190px; }
        .layui-form-label{ width: 120px !important; }
        .layui-form-switch { margin-top: 6px; height: 25px; }
        .layui-form-mid{ margin-right: 0; }
        .layui-iconfonts  {float: left;}
        .layui-iconfonts .layui-anim { width: 300px !important; left: auto !important; right: 0; max-height: 310px !important;}
        .systemmoduletree {
            position: absolute;
            left: 120px;
            background-color: #fff;
            padding: 5px;
            z-index: 1000;
            box-shadow: 0 0 24px rgba(0,0,0,.18);
            opacity: 0;
            width: 220px;
            height: 0;
            display: none;
        }
        .systemmoduletree.active {
            display: block;
            opacity: 1;
            height: auto;
            max-height: 330px;
            overflow: auto;
            transition: all .5s;
        }
    </style>
}
<div class="layui-container" style="background-color: #fff;">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
        <legend>@ViewBag.PageTitle - 模块修改</legend>
    </fieldset>
    <form class="layui-form" action="">
        <input class="layui-hide" type="text" name="@Model.nameof(m => m.Id)" value="@Model.Id" />
        <div class="layui-form-item">
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.ParentIdDisplay))</label>
                <input type="text" name="@Model.nameof(m => m.ParentIdDisplay)" value="@Model.ParentIdDisplay" readonly lay-verify="required" placeholder="请选择所属父级" autocomplete="off" class="layui-input" style="width: 220px;">
                <input type="text" name="@Model.nameof(m => m.ParentId)" value="@Model.ParentId" class="layui-hide" />
                <div id="systemmoduletree" class="layui-row systemmoduletree"></div>
            </div>
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.IconCssClass))</label>
                <input type="text" id="@Model.nameof(m => m.IconCssClass)" name="@Model.nameof(m => m.IconCssClass)" value="@Model.IconCssClass" lay-filter="iconFonts" required lay-verify="required" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.ModuleName))</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.nameof(m => m.ModuleName)" value="@Model.ModuleName" lay-verify="required" placeholder="请输入系统模块名称" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">建议使用英文，区分大小写</div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.DisplayName))</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.nameof(m => m.DisplayName)" value="@Model.DisplayName" placeholder="请输入显示名称" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">如不填写，则使用系统模块名做显示</div>
        </div>
        <div class="layui-form-item">
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.ModuleTypeDisplay))</label>
                <select asp-for="ModuleType" asp-items="@Model.AvailableModuleTypes" lay-verify="required" lay-filter="ModuleTypeSelect">
                    <option value="">请选择...</option>
                </select>
            </div>
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.OpenOnNewWindow))</label>
                <input type="checkbox" name="@Model.nameof(m => m.OpenOnNewWindow)" value="@((int)Model.OpenOnNewWindow)" lay-skin="switch" lay-text="ON|OFF" @if (Model.OpenOnNewWindow == EntityEnumConfig.YesorNo.YES) { <text> checked</text> } />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.UrlRoute))</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.nameof(m => m.UrlRoute)" value="@Model.UrlRoute" lay-verify="requiredwhenmodulepage" placeholder="请选输入Url" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">当系统模块类型为"系统模块"时，此项不能为空</div>
        </div>
        <div class="layui-form-item">
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.DisplayOrder))</label>
                <input type="text" name="@Model.nameof(m => m.DisplayOrder)" lay-verify="required" value="@Model.DisplayOrder" placeholder="请输入排序号" autocomplete="off" class="layui-input" style="width: 45%;" />
            </div>
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.IsActive))</label>
                <input type="checkbox" name="@Model.nameof(m => m.IsActive)" value="@((int)Model.IsActive)" lay-skin="switch" lay-text="ON|OFF" @if (Model.IsActive == EntityEnumConfig.YesorNo.YES) { <text> checked</text> } />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<SystemModuleModel>(m => m.ModuleAssignedButtonNames))</label>
            @foreach (var btntype in datadicButtons.Data.GroupBy(b => b.ButtonType).Select(g => g.Key).ToList())
            {
                <div class="layui-card layui-input-block" style="margin-bottom: 5px; border: 1px solid #f6f6f6;">
                    <div class="layui-card-header">
                        @datadicButtons.Data.FirstOrDefault(b => b.ButtonType == btntype).ButtonTypeDisplay
                    </div>
                    <div class="layui-card-body">
                        @foreach (var btnitem in datadicButtons.Data.Where(b => b.ButtonType == btntype))
                        {
                            <input type="checkbox" name="datadicbtn" value="@btnitem.Id" title="@btnitem.ButtonName" lay-skin="primary" />
                        }
                    </div>
                </div>
            }
            <input class="layui-hide" name="@Model.nameof(m => m.ModuleAssignedButtons)" value="@SystemModuleAssignedButtons" />
        </div>
        <div style="width: 100%; height: 50px; line-height: 50px;"></div> <!--占位符，防止底部固定提交栏遮挡最下层区域-->
        <div class="layui-form-item footerbar">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="systemmoduleedit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

@section scripts{
    <script type="text/javascript">
    layui.use(['form', 'element', 'tree', 'IconFonts', 'notice','iziToast'], function () {
        var form = layui.form,
            element = layui.element,
            tree = layui.tree,
            IconFonts = layui.IconFonts,
            notice = Util.notice !== null && Util.notice() !== null
                   ? Util.notice() : layui.notice,
            iziToast = layui.iziToast,
            lodash = _;
        var initPageComponents = function () {
            iziToast.loading("Loading...");
            IconFonts.render({
                elem: '#IconCssClass', //选择器ID
                type: 'fontClass',// 数据类型：fontClass/layui_icon，
                search: true,     // 是否开启搜索：true/false
                page: true,       // 是否开启分页
                limit: 20,        // 每页显示数量，默认12
                click: function (data) {// 点击回调
                    let iconclass = data.icon;
                    if (!iconclass.startsWith("fa ")) iconclass = 'fa ' + data.icon;
                    $("#IconCssClass").val(iconclass);
                },
                success: function (d) {
                    var $iconCssClass = $("#IconCssClass");
                    if ($iconCssClass.val().length > 0) {
                        let selectedFont = lodash.split($iconCssClass.val(), ' ');
                        IconFonts.checkIcon("iconFonts", selectedFont[1], "fontClass");
                    }
                }
            });
            initSystemModuleTree(iziToast);
            initDataDicButtons();
        },
        initSystemModuleTree = function (iziToast) {
            let modelParentId = @Model.ParentId,
                modelId = @Model.Id;
            if (modelParentId === 0 && modelId !== 0) {
                iziToast.destroy();
                return false; //根节点不能指定父级
            }
            let $treeContainer = $("div.systemmoduletree");
            httpapi.fetchGet('/api/system/getsystemmoduletreeall').then(res => {
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    notice.error(res.message);
                    iziToast.destroy();
                }
                else {//Success
                    tree.render({
                        elem: $treeContainer,
                        id: "systemmoduletree",
                        onlyIconControl: true,
                        data: res.data,
                        click: function (obj) {
                            if (obj.data.id) {
                                $("input[name='ParentIdDisplay']").val(obj.data.title);
                                $("input[name='ParentId']").val(obj.data.id);
                            }
                        }
                    });
                    iziToast.destroy();
                }
            }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
            $("input[name='ParentIdDisplay']").click(function () {
                $("div#systemmoduletree").addClass("active");
            });
            $("div#systemmoduletree").mouseleave(function () {
                $(this).removeClass("active");
            });
        },
        disableDataDicButtons = function () {
            //只有系统模块可以分配操作按钮
            let $ModuleTypeSelect = $("select[name='ModuleType']"),
                result = false;
            if ($ModuleTypeSelect.val() !== "" && $ModuleTypeSelect.val()!== "ModulePage") {
                $("input[name='datadicbtn']:checked").prop("checked", false);
                $("input[name='datadicbtn']").attr("disabled", "disabled");
                result = true;
            } else {
                $("input[name='datadicbtn']").removeAttr("disabled");
                result = false;
            }
            form.render();
            return result;
        },
        initDataDicButtons = function () {
            if (disableDataDicButtons()) return false;
            let SystemModuleAssignedButtons = [@SystemModuleAssignedButtons];
            if (SystemModuleAssignedButtons.length > 0) {
                $.each(SystemModuleAssignedButtons, function (i, value) {
                    let btnid = value;
                    if (typeof value === "string") btnid = parseInt(value);
                    $("input[name='datadicbtn']").each(function () {
                        if (parseInt($(this).val()) === btnid)
                            $(this).prop("checked", true);
                    });
                });
                form.render(); 
            }
        };

        initPageComponents();  
        form.on('select(ModuleTypeSelect)', function (data) {
            $(data.elem).val(data.value);
            initDataDicButtons();
        });

        form.verify({
            requiredwhenmodulepage: function (value, item) { //value：表单的值、item：表单的DOM对象
                let $ModuleTypeSelect = $("select[name='ModuleType']");
                if ($ModuleTypeSelect.val() !== "") {
                    if ($ModuleTypeSelect.val() === "ModulePage" && value.trim() === "") {
                        $(item).focus();
                        return "当系统模块类型为'系统模块'时，Url不能为空";
                    }
                }
            }
        });  
        //监听提交
        form.on("submit(systemmoduleedit)", function (data) {
            var postData = data.field;
            if (postData.hasOwnProperty("ModuleAssignedButtons")) {
                postData.ModuleAssignedButtons = [];
                $("input[name='datadicbtn']:checked").each(function () {
                    postData.ModuleAssignedButtons.push(parseInt($(this).val()));
                });
            }
            if (postData.hasOwnProperty("datadicbtn")) {
                delete postData["datadicbtn"];
            }
            iziToast.loading("提交中，请稍候"); 
            httpapi.fetchPost('/api/system/systemmodule/edit', data.field).then(res => {
                iziToast.destroy();
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    iziToast.error({
                        title: '修改失败',
                        message: res.message
                    });
                } else {//Success
                    iziToast.loading(res.message);
                    $.wait(2000).then(function () {
                        Util.MainWindowRedirect("/backend");
                    });
                }
            }).catch(error => notice.error("对不起，登录过程出现未知错误，请您联系系统管理员！"));
                
            return false;
        });
    });
    </script>
}
